package com.ruoyi.project.kbjz.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/pay")
public class PaymentController {
    //创建支付宝支付需要的常量值

    // 应用标识， 需要使用支付宝扫码登录《支付宝沙箱环境地址》中查看
    private final String APP_ID = "2021000117600652";
    // 应用私钥， 需要安装支付宝开放平台助手，在助手中---生成密钥 找
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzeOnGVhR1DlZEgsc1ZmqipoCEzf2HmbvmUFYGstC9zCtKxZcPMF+YTSPWqTl/FH2UWeEOCITmST6RB8TCAR1fPujE7aFxGm6w4tsQa3J++0V8w7ryZe9GOmysjRDx7YKMYuooIvns3lAu/gOuwF3rzxrcsFOlK8d06Q3PfykAcGkEG+eeO8kkcQlT6MyZj9QF7vLR2uizX8+nKJwqBLkpY41Ngb5NLu2EF27zwQ0uvm1/1pdiug+ayzCORlN5zbkB3sY06jXkT9Dl6M5yy10ZxYRhL/ozTQLEzqptjAkNH8Nkr4LaMnaAdshDnDjp7BoAYu2F6LnJgDgIh/vZVf2LAgMBAAECggEAIhxREkk6CiV3b/4LLrMQgWlz88nS7friI5wRPaSu1+P+Nm/njhN7l87RiPMQ4n5af9+1Tp1/5OT250m6s8TSeE/UndksXfrQHv5+9Ff3ovrO8i+hUIDfQVHJZeJJ3jFuJpCGQKqlJcf7JXNR79zP/QmX6Wn5++KePjItVcqtWE+zTQf2CcSzJOp6Q4cGVSbRVJrPrEQp6La4bC01zbZ/v4tvCgb60iELes+WWfzjCkloGOpKSozznvyIKTeMYU2LJHBCi6MrOX3S3Zw2SRDQERmnQJcTDKpJILMu18o+Kptwu7hnj53ftxMZFlxfJM2vxp3I++nqxhvFF+f21UagAQKBgQDrtz3ib1enEwGQOVwtfv+M4HnBHKgbt+3g+LK9N6jWKXWsyqXCx+aC3lsDIprl2E0HRh4UNYSLRrBCAdhmgVPrBC/pFXUVA6nEysfs6SsgZ6krbpLkCA169wstn2k4nXBhjCYuCni1TDypB92FX0KpapF2n4j4YRsQZ7wyXeHviwKBgQDC6qRpHT34G62j5MIE9SJ6NdCF6L9Ad+Wo6IyFHS8NdcCGymwT/wmoY722bkRNqgpslw/Au/CpvC3bhbG3MCyZ1FgSUIBVESFvrFRDlk4BIwfzyLiiV13+Sc+p9ZL9Yyf/NjtUUVcd/7g6VR4dkU3DsVOHJHb3LBVYjKIM813qAQKBgQDEFmj10LgzNb1sNDt5YZfHownGW0eB342VRG60t/PNTSomd2JT2iXpon5F6mi/YiQaM/tbxnWfw0tnbc+O3nFoJdCRbxc6RxTYr/SHIiWNTI7Poamy5vwH2jHDX0SSI27Ux1kPnghykZw45WEjzW5QL2YZL3grX+S6zgEiSTVmJwKBgE3gxIn/FghwvqMSPncOnpTntYYbZXbTsN4Y9DQnYepl1uPEMwSWTPyLxXwDeKTzQLD8dl3SeajHuCbStxvzUo6v6fR/V5clfg+Jci2C+2222nGMDEFI2RRF14QXy4AUQyHUQEZDLaSdzLT510uHB+QdkLsZVbMSWQEFR6YXAroBAoGAB3K522n9HHagr91vAog8MGJAoBdzEWaFEczEjxp7au6Rxk/5ZM9E+HxTjwDISXSpCEQmHScALng/XN2LH2e7JQw34iEKTAehWRzbkKy0rNW7ZPVgz8xPGM7E3hUhiQNcvmwhHIJF7l0ZQgc4SFf7jvCP1pEB6/aonEUJJAhRfbI=";
    // 编码格式
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvGRCVC8zeCl1p8IwzyzP8qvPz3jON9VoPS3QuByxY65E4N1QQlqP3FC4zpo094LFpdVhsZNQeC4n3D0ZFBZoOuKF4U/MxeJAPR5hVpj8cZPP4IQyUFOOsSXBfvuEQmVthaQwo6tkiB2ozRX+3TjbnjePJOGypcd6VVeVs+vld7Zm1DzVeABjcPupUYSoT7DhbKAm668uuHiruEGhD8w3Pe8o2fsUHASUbZgD/HYXO3wwgoNXw2RynEn6GNPN8zL0pG+HGTacEHCX0Dbtm2DrTSNIdmAnK7x3y8UP+h4+XpR+lNWqlE/1eyBKOF0nKpTDhq3OpxQlOn7uXIlSSmlqZwIDAQAB";
    // 沙箱路径接口，正是路径应为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    // 参数返回格式
    private final String FORMAT = "JSON";
    // 签名方式
    private final String SIGN_TYPE = "RSA2";
    // 支付宝异步通知路径，付款完毕后会异步调用本项目的方法，必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyURL";
    // 支付宝同步通知路径，也就是当付款完毕后跳转本项目的页面，可以不是公网地址
    private final String RETURN_URL = "http://127.0.0.1/returnURL";

    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse response) throws IOException {
        // 实例化客户端,填入所需参数
        // 网关地址 应用标识 应用私钥 传输格式 编码格式 支付宝公钥 签名类型
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Integer.toString(100);
        //订单名称，必填
        String subject ="奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        //商品描述，可空
        String body = "尊敬的会员欢迎购买奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + CHARSET);
        response.getWriter().write(form);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
    @RequestMapping(value = "/re", method = RequestMethod.GET)
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();){
             String name = (String) iter.next();
        String[] values = (String[]) requestParams.get(name);
        String valueStr = "";
        for (int i = 0; i < values.length; i++) {
            valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
        }
        // 乱码解决，这段代码在出现乱码时使用
        valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
        params.put(name, valueStr);
    }
    System.out.println(params);//查看参数都有哪些
    boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
    //验证签名通过
    if(signVerified){
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("商户订单号="+out_trade_no);
        System.out.println("支付宝交易号="+trade_no);
        System.out.println("付款金额="+total_amount);
        //支付成功，修复支付状态
        /*payService.updateById(Integer.valueOf(out_trade_no));*/
        System.out.println("ok");//跳转付款成功页面
    }else{
        System.out.println("no");//跳转付款失败页面
    }
}
}
